classdef LastOrderReader < handle
    properties (SetAccess = private)
        fileNameConst = 'lastOrder';
        fileName = '';
        openOptions;

        currentLastOrder;
    end
    
    methods 
        %%
        function obj = LastOrderReader( osxOpenOptions )
            obj.openOptions = osxOpenOptions;
            obj.fileName = strcat( obj.fileNameConst, datestr(today), '.csv' );
            writeChangesToFile( obj.fileName, {datestr(now)}, 'w' );
        
            tempStr = [ obj.openOptions.call_string obj.openOptions.put_string ];
            obj.currentLastOrder = OptionMap( tempStr );
            tempKeys = obj.currentLastOrder.optionMap.keys;
            for i = 1:length( tempKeys )
                 obj.currentLastOrder.optionMap( tempKeys{i} ) = [ 0 0 ]; %[Last trade, trades ]
            end
            
            obj.sampleLastTrade();
        end
        
           
        
        %%
        function sampleLastTrade( obj )
                
                %Read data (localhost is set up separately by PrimeTrader software)
                try
                    tempStr = [ obj.openOptions.call_string obj.openOptions.put_string ];
                    urlString = urlread( strcat('http://localhost:8678/quotes/', tempStr ) );
                catch
                    error( 'Error reading data. Make sure url string is correctly specified and that PrimeTrader is running')
                end

                lineBreakIndices =  strfind( urlString, '</tr>');
                lineStartIndices =  strfind( urlString, '<tr>');


                %Process urlstring
                ticker = '';
                changes = {};
                for i = 2:length(lineBreakIndices)
                    line = urlString( lineStartIndices(i)+4:lineBreakIndices(i)-1 );
                    td_start = strfind( line, '<td>' );
                    td_end =  strfind( line, '</td>' );

                    ticker = line( td_start(5)+4:td_end(5)-1 );
                    trades = line( td_start(21)+4:td_end(21)-1 );
                    if isempty(trades)
                        trades = '0';
                    end
                    tempCurrLastTrade = obj.currentLastOrder.optionMap( ticker );
                    if  tempCurrLastTrade(2) ~= str2double( trades );
                        timestamp = line( td_start(4)+4:td_end(4)-1 );
                        lastTrade = line( td_start(17)+4:td_end(17)-1 );
                        changes{end+1,1} = [ticker ',' timestamp ',' lastTrade];
                    end
                end
                writeChangesToFile( obj.fileName, changes, 'a' );
        end

        
    end
end
    